package cn.itsource.smartcampus.controller;

import cn.itsource.smartcampus.util.AjaxResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SessionController {

    /**
     * 创建Session对象
     * @param request
     * @param session
     * @return
     */
    @GetMapping("/sess")
    public AjaxResult<Void> testCookie(HttpServletRequest request, HttpSession session) {
        // 1.使用请求对象获取Session对象
        HttpSession sessionRequest = request.getSession();
        // 2.直接接收一个Session对象，两种方式获取到的是同一个Session对象
        System.out.println(sessionRequest == session);
        // 3.响应
        return AjaxResult.ok("访问成功！");
    }

    /**
     * 设置Session值
     * @param request
     * @return
     */
    @GetMapping("/sess2")
    public AjaxResult<Void> testCookie1(HttpServletRequest request) {
        // 1.获取Session对象
        HttpSession session = request.getSession();
        // 2.设置键值对
        session.setAttribute("name","张三");
        // 3.响应
        return AjaxResult.ok("访问成功！");
    }


    /**
     * 获取Session值
     * @param request
     * @return
     */
    @GetMapping("/sess3")
    public AjaxResult<Void> testCookie2(HttpServletRequest request) {
        // 1.获取Session对象
        HttpSession session = request.getSession();
        // 2.获取数据
        Object name = session.getAttribute("name");
        System.out.println(name);
        // 3.响应
        return AjaxResult.ok("访问成功！");
    }

    /**
     * 删除数据
     * @param request
     * @return
     */
    @GetMapping("/sess4")
    public AjaxResult<Void> testCookie3(HttpServletRequest request) {
        // 1.获取Session对象
        HttpSession session = request.getSession();
        // 2.删除数据
        session.removeAttribute("name");
        // 3.响应
        return AjaxResult.ok("访问成功！");
    }


    /**
     * 销毁Session对象
     * @param request
     * @return
     */
    @GetMapping("/sess5")
    public AjaxResult<Void> testCookie(HttpServletRequest request) {
        // 1.获取Session对象
        HttpSession session = request.getSession();
        // 2.销毁对象
        session.invalidate();
        // 3.响应
        return AjaxResult.ok("访问成功！");
    }
}
